package team.nine.kuaichezuche.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import team.nine.kuaichezuche.model.RentalOrder;
import team.nine.kuaichezuche.service.RentalOrderService;
import team.nine.kuaichezuche.service.UserService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 租车订单控制器
 */
@RestController
@RequestMapping("/api/order")
public class RentalOrderController {
    
    @Autowired
    private RentalOrderService rentalOrderService;
    
    @Autowired
    private UserService userService;
    
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    /**
     * 创建租车订单
     * 接收用户令牌、解析订单信息并存储到数据库，设置订单状态为0（待支付）并返回状态码6000
     */
    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createOrder(@RequestHeader("Authorization") String token, @RequestBody Map<String, Object> requestBody) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 验证令牌
            if (token == null || !token.startsWith("Bearer ")) {
                response.put("status", "error");
                response.put("code", 3001);
                response.put("message", "无效的令牌格式");
                return ResponseEntity.status(401).body(response);
            }
            
            // 提取令牌内容
            String authToken = token.substring(7);
            
            // 解析用户ID
            String[] tokenParts = authToken.split("_");
            if (tokenParts.length < 5 || !tokenParts[1].startsWith("u")) {
                response.put("status", "error");
                response.put("code", 3001);
                response.put("message", "无效的令牌格式");
                return ResponseEntity.status(401).body(response);
            }
            
            // 提取用户ID
            String userIdStr = tokenParts[1].substring(1); // 移除前缀 'u'
            Long userId;
            try {
                userId = Long.parseLong(userIdStr);
            } catch (NumberFormatException e) {
                response.put("status", "error");
                response.put("code", 3001);
                response.put("message", "无效的用户ID格式");
                return ResponseEntity.status(401).body(response);
            }
            
            // 验证用户是否存在
            try {
                userService.getUserByToken(authToken);
            } catch (Exception e) {
                response.put("status", "error");
                response.put("code", 3001);
                response.put("message", "令牌无效或用户不存在");
                return ResponseEntity.status(401).body(response);
            }
            
            // 提取请求参数
            Integer vehicleId = requestBody.get("vehicleId") != null ? Integer.parseInt(requestBody.get("vehicleId").toString()) : null;
            String startTimeStr = requestBody.get("startTime") != null ? requestBody.get("startTime").toString() : null;
            String endTimeStr = requestBody.get("endTime") != null ? requestBody.get("endTime").toString() : null;
            Double totalPrice = requestBody.get("totalPrice") != null ? Double.parseDouble(requestBody.get("totalPrice").toString()) : null;
            
            // 验证请求参数
            if (vehicleId == null || startTimeStr == null || endTimeStr == null || totalPrice == null) {
                response.put("status", "error");
                response.put("code", 4000);
                response.put("message", "参数不完整");
                return ResponseEntity.status(400).body(response);
            }
            
            // 解析日期
            Date startTime;
            Date endTime;
            try {
                startTime = dateFormat.parse(startTimeStr);
                endTime = dateFormat.parse(endTimeStr);
            } catch (ParseException e) {
                response.put("status", "error");
                response.put("code", 4000);
                response.put("message", "日期格式不正确，应为yyyy-MM-dd HH:mm:ss");
                return ResponseEntity.status(400).body(response);
            }
            
            // 创建订单
            RentalOrder order = rentalOrderService.createOrder(vehicleId, userId, startTime, endTime, totalPrice);
            
            // 构造成功响应
            response.put("status", "success");
            response.put("code", 6000);
            response.put("message", "订单创建成功，等待支付");
            response.put("orderId", order.getId());
            
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            // 处理参数错误
            response.put("status", "error");
            response.put("code", 4000);
            response.put("message", e.getMessage());
            return ResponseEntity.status(400).body(response);
        } catch (Exception e) {
            // 处理其他异常
            response.put("status", "error");
            response.put("code", 5000);
            response.put("message", "订单创建失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
    
    /**
     * 支付租车订单
     * 接收支付信息，更新订单状态为1（已支付）和车辆状态为1（已租出）并返回状态码6001
     */
    @PostMapping("/pay")
    public ResponseEntity<Map<String, Object>> payOrder(@RequestHeader("Authorization") String token, @RequestBody Map<String, Object> requestBody) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 验证令牌
            if (token == null || !token.startsWith("Bearer ")) {
                response.put("status", "error");
                response.put("code", 3001);
                response.put("message", "无效的令牌格式");
                return ResponseEntity.status(401).body(response);
            }
            
            // 提取令牌内容
            String authToken = token.substring(7);
            
            // 验证用户是否存在
            try {
                userService.getUserByToken(authToken);
            } catch (Exception e) {
                response.put("status", "error");
                response.put("code", 3001);
                response.put("message", "令牌无效或用户不存在");
                return ResponseEntity.status(401).body(response);
            }
            
            // 提取订单ID
            Integer orderId = requestBody.get("orderId") != null ? Integer.parseInt(requestBody.get("orderId").toString()) : null;
            
            // 验证订单ID
            if (orderId == null) {
                response.put("status", "error");
                response.put("code", 4000);
                response.put("message", "订单ID不能为空");
                return ResponseEntity.status(400).body(response);
            }
            
            // 处理支付
            RentalOrder order = rentalOrderService.payOrder(orderId);
            
            // 构造成功响应
            response.put("status", "success");
            response.put("code", 6001);
            response.put("message", "订单支付成功");
            response.put("orderId", order.getId());
            
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            // 处理参数错误或业务逻辑错误
            response.put("status", "error");
            response.put("code", 4000);
            response.put("message", e.getMessage());
            return ResponseEntity.status(400).body(response);
        } catch (Exception e) {
            // 处理其他异常
            response.put("status", "error");
            response.put("code", 5000);
            response.put("message", "订单支付失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
    
    /**
     * 取消租车订单
     * 接收取消信息，设置订单状态为3（已取消）并返回状态码6002
     */
    @PostMapping("/cancel")
    public ResponseEntity<Map<String, Object>> cancelOrder(@RequestHeader("Authorization") String token, @RequestBody Map<String, Object> requestBody) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 验证令牌
            if (token == null || !token.startsWith("Bearer ")) {
                response.put("status", "error");
                response.put("code", 3001);
                response.put("message", "无效的令牌格式");
                return ResponseEntity.status(401).body(response);
            }
            
            // 提取令牌内容
            String authToken = token.substring(7);
            
            // 验证用户是否存在
            try {
                userService.getUserByToken(authToken);
            } catch (Exception e) {
                response.put("status", "error");
                response.put("code", 3001);
                response.put("message", "令牌无效或用户不存在");
                return ResponseEntity.status(401).body(response);
            }
            
            // 提取订单ID
            Integer orderId = requestBody.get("orderId") != null ? Integer.parseInt(requestBody.get("orderId").toString()) : null;
            
            // 验证订单ID
            if (orderId == null) {
                response.put("status", "error");
                response.put("code", 4000);
                response.put("message", "订单ID不能为空");
                return ResponseEntity.status(400).body(response);
            }
            
            // 处理取消
            RentalOrder order = rentalOrderService.cancelOrder(orderId);
            
            // 构造成功响应
            response.put("status", "success");
            response.put("code", 6002);
            response.put("message", "订单已取消");
            response.put("orderId", order.getId());
            
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            // 处理参数错误或业务逻辑错误
            response.put("status", "error");
            response.put("code", 4000);
            response.put("message", e.getMessage());
            return ResponseEntity.status(400).body(response);
        } catch (Exception e) {
            // 处理其他异常
            response.put("status", "error");
            response.put("code", 5000);
            response.put("message", "订单取消失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
    
    /**
     * 查询订单状态
     */
    @GetMapping("/status/{orderId}")
    public ResponseEntity<Map<String, Object>> getOrderStatus(@RequestHeader("Authorization") String token, @PathVariable Integer orderId) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 验证令牌
            if (token == null || !token.startsWith("Bearer ")) {
                response.put("status", "error");
                response.put("code", 3001);
                response.put("message", "无效的令牌格式");
                return ResponseEntity.status(401).body(response);
            }
            
            // 提取令牌内容
            String authToken = token.substring(7);
            
            // 验证用户是否存在
            try {
                userService.getUserByToken(authToken);
            } catch (Exception e) {
                response.put("status", "error");
                response.put("code", 3001);
                response.put("message", "令牌无效或用户不存在");
                return ResponseEntity.status(401).body(response);
            }
            
            // 查询订单
            RentalOrder order = rentalOrderService.getOrderById(orderId);
            if (order == null) {
                response.put("status", "error");
                response.put("code", 4000);
                response.put("message", "订单不存在");
                return ResponseEntity.status(404).body(response);
            }
            
            // 构造成功响应
            Map<String, Object> orderInfo = new HashMap<>();
            orderInfo.put("orderId", order.getId());
            orderInfo.put("status", order.getStatus());
            orderInfo.put("vehicleId", order.getVehicleId());
            orderInfo.put("startTime", dateFormat.format(order.getStartTime()));
            orderInfo.put("endTime", dateFormat.format(order.getEndTime()));
            orderInfo.put("totalPrice", order.getTotalPrice());
            orderInfo.put("createdAt", dateFormat.format(order.getCreatedAt()));
            
            response.put("status", "success");
            response.put("code", 2000);
            response.put("message", "查询成功");
            response.put("data", orderInfo);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 处理异常
            response.put("status", "error");
            response.put("code", 5000);
            response.put("message", "查询失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}